<?php

namespace App\Http\Controllers\Admin;

use Validator;
use Illuminate\Http\Request;
use App\Model\Common\Album;
use App\Model\Common\AdminLog;

class AlbumController extends CommonController{
    protected $defaultSort = 'rank';
    protected $defaultOrder = 'desc';
    protected $perpage = 12;
    public function add(Request $request)
    {
        if ('GET' == $request->method()) {
            return $this->fetch();
        } else {
            $data = $request->all();
            $validator = Validator::make($data, [
                'title' => 'required|min:1|max:24',
                'description' => 'required|min:1|max:60',
            ]);
            if ($validator->fails()) {
                return $this->output(10005, $validator->errors());
            }

            $path = $this->upload('img');

            if (false === $path) {
                return $this->output(10005, $this->getUploadError());
            }
            $data['pic'] = $path;
            $m = new Album();

            $re = $m->fillData($data)->save();

            if ($re) {
                if (method_exists($m, 'refreshCache')) {
                    $m->refreshCache($m, 'insert');
                }
                AdminLog::log($request, $m);
                return $this->output(0, '新增成功', $re);
            } else {
                return $this->output(10001, '新增失败'.$m->getError(), null);
            }
        }
    }
}